
import utils.DataUtils;
import utils.InputUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 客户端：套接字(url:port)建立连接、发送命令、接收数据
 */
public class Client {
    private static OutputStream out;
    private static InputStream in;
    private static byte[] buffer=new byte[1024];
    private static int read=0;
    public static void main(String[] args) {
        if (args.length==0){
            initConnect(8888,"127.0.0.1");
        }else {
            initConnect(Integer.valueOf(args[0]), args[1]);
        }
    }

    private static void initConnect(int port,String host) {
        try(Socket socket=new Socket(host,port)) {
            System.out.println("Client is connecting to port "+port);
            sendData(socket);
        } catch (IOException e) {
            System.out.println("Exception caught when client is connecting to port "+port);
        }
    }

    private static void sendData(Socket socket) throws IOException {
        in=socket.getInputStream();
        out=socket.getOutputStream();
        while (true){
            String arg = InputUtil.readLine();
            if ("exit".equals(arg)) {
                System.out.println("Program exit , Bye~");
                break;
            }
            //arg参数校验与封装
            arg = DataUtils.getData(arg);
            out.write(arg.getBytes(StandardCharsets.UTF_8));
            out.flush();
            acceptData();
        }
    }

    private static void acceptData() throws IOException {
        while ((read=in.read(buffer,0,buffer.length))!=-1){
            String data = new String(buffer, 0, read);
            if ("END".equals(data))break;
            System.out.println(data);
        }
    }
}
